相关疑难解决方法(0)

C++,是否可以直接调用构造函数,而不需要新的?

new如果我已经有对象的内存,我可以显式调用构造函数而不使用吗?

class Object1{
    char *str;
public:
    Object1(char*str1){
        str=strdup(str1);
        puts("ctor");
        puts(str);
    }
    ~Object1(){
        puts("dtor");
        puts(str);
        free(str);
    }
};

Object1 ooo[2] = {
     Object1("I'm the first object"), Object1("I'm the 2nd")
};

do_smth_useful(ooo);
ooo[0].~Object1(); // call destructor
ooo[0].Object1("I'm the 3rd object in place of first"); // ???? - reuse memory
Run Code Online (Sandbox Code Playgroud)

c++ constructor placement-new

51
推荐指数
4
解决办法
3万
查看次数

在构造函数中抛出异常时,不会调用析构函数

为什么在此代码中不调用析构函数?

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

class MyClass {
boost::scoped_ptr<int> ptr;
public:
MyClass() : ptr(new int) { *ptr = 0; throw; std::cout<<"MyClass Allocated\n"; }
~MyClass() { std::cout<<"MyClass De-allocated\n"; }
int increment() { return ++*ptr; }
};

int main()
{
    boost::scoped_ptr<MyClass> myinst(new MyClass);
    std::cout << myinst->increment() << '\n';
    std::cout << myinst->increment() << '\n';
}
Run Code Online (Sandbox Code Playgroud)

编辑

从答案中,了解当构造函数中发生异常时,不会调用析构函数.但是如果异常发生在main()中,即在完全实例化MyClass对象之后,是否会调用MyClass析构函数?如果没有,那为什么它是一个智能指针?

添加代码

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

class MyClass {
    boost::scoped_ptr<int> ptr;
    public:
    MyClass() : ptr(new int) { *ptr = 0; std::cout<<"MyClass Allocated\n"; }
    ~MyClass() { std::cout<<"MyClass De-allocated\n"; …
Run Code Online (Sandbox Code Playgroud)

c++ boost scoped-ptr

8
推荐指数
2
解决办法
5112
查看次数

标签 统计

c++ ×2

boost ×1

constructor ×1

placement-new ×1

scoped-ptr ×1