Boost logo

Boost Users :

Subject: Re: [Boost-users] Safe to pass dereferenced anonymous shared_ptr?
From: Scott Mueller (smueller_at_[hidden])
Date: 2013-11-05 19:57:04


Hello,

Q1: Is the below code dangerous?
A1: Short answer: no. For the long answer, see the end of this email.

Q2: Is the anonymous shared_ptr deleted before function f returns?
A2: No, it is deleted afterward.

-----Original Message-----
From: Boost-users [mailto:boost-users-bounces_at_[hidden]] On Behalf Of Chris Stankevitz
Sent: Tuesday, November 05, 2013 3:13 PM
To: boost-users_at_[hidden]
Subject: [Boost-users] Safe to pass dereferenced anonymous shared_ptr?

...

#include <iostream>
#include <boost/make_shared.hpp>

void f(const int& i)
{
  std::cout << "i = " << i << std::endl; }

int main()
{
  f(*boost::make_shared<int>(42));

  return 0;
}
-----/Original Message-----

As far as I understand the standard, any temporaries that are created for an expression are destroyed after the result is obtained. With this in mind, the boost::shared_ptr<> will be destroyed after the invocation of f().
>From 12.2.3 of ISO/IEC 14882:2011(E):
When an implementation introduces a temporary object of a class that has a non-trivial constructor (12.1, 12.8), it shall ensure that a constructor is called for the temporary object. Similarly, the destructor shall be called for a temporary with a non-trivial destructor (12.4). Temporary objects are destroyed as the last step in evaluating the full-expression (1.9) that (lexically) contains the point where they were created. This is true even if that evaluation ends in throwing an exception. The value computations and side effects of destroying a temporary object are associated only with the full-expression, not with any specific subexpression.

Yep, I paid the 30 bucks. ;)

Best regards,

M. Scott Mueller


Boost-users list run by williamkempf at hotmail.com, kalb at libertysoft.com, bjorn.karlsson at readsoft.com, gregod at cs.rpi.edu, wekempf at cox.net