来自对象

时间:2017-03-27 20:53:57

标签: c++ shared-ptr

在下面的示例中,我有一个成员int actual_int的类。在另一个类中,我希望对此int有一个shared_ptr。但是,当我查询shared_ptractual_int的地址时,它们是不同的。它是实现的结果,还是共享指针的预期行为?

test.hpp

#include <iostream>

class FooMember {
public:
    FooMember();
    virtual void FooMember_printer();
};

class Foo {
private:
    int actual_int;
public:
    std::unique_ptr<FooMember> foo_member;

    Foo();
    void Foo_printer();
};

TEST.CPP

#include "test.hpp"

// Hidden FooMember class
class FooMemberH : public FooMember {
private:
    std::shared_ptr<int> ptr_to_secret_int;
public:
    FooMemberH(std::shared_ptr<int> from_int) : ptr_to_secret_int(std::move(from_int)) {};

    void FooMember_printer() {
        std::cout << this->ptr_to_secret_int.get() << " " << *(this->ptr_to_secret_int) << std::endl;
        return;
    };
};

// Construct FooMember
FooMember::FooMember() {};

// Construct Foo
Foo::Foo() {
    // Make a secret int
    this->actual_int = 2;

    // Make a FooMemberH
    this->foo_member = std::make_unique<FooMemberH>(FooMemberH(std::make_shared<int>(this->actual_int)));
};

// Foo: Print the secret int
void Foo::Foo_printer() {
    std::cout << &(this->actual_int) << " " << this->actual_int << std::endl;
    return;
};

// FooMember: Nothing to print
void FooMember::FooMember_printer() {
    std::cout << "I have no secret int." << std::endl;
    return;
};

int main() {

    Foo my_foo;
    my_foo.Foo_printer();
    my_foo.foo_member->FooMember_printer();

    return 0;
};

编辑:根据评论:我们的想法是在这里使用共享指针代替常规指针:

test.hpp

#include <iostream>

class FooMember {
public:
    FooMember();
    virtual void FooMember_printer();
};

class Foo {
private:
    int actual_int;
public:
    FooMember *foo_member;

    Foo();
    void Foo_printer();
};

TEST.CPP

#include "test.hpp"

// Hidden FooMember class
class FooMemberH : public FooMember {
private:
    const int *ptr_to_secret_int;
public:
    FooMemberH(const int & from_int) {
        this->ptr_to_secret_int = &from_int;
    };

    void FooMember_printer() {
        std::cout << this->ptr_to_secret_int << " " << *(this->ptr_to_secret_int) << std::endl;
        return;
    };
};

// Construct FooMember
FooMember::FooMember() {};

// Construct Foo
Foo::Foo() {
    // Make a secret int
    this->actual_int = 2;

    // Make a FooMemberH
    this->foo_member = new FooMemberH(this->actual_int);
};

// Foo: Print the secret int
void Foo::Foo_printer() {
    std::cout << &(this->actual_int) << " " << this->actual_int << std::endl;
    return;
};

// FooMember: Nothing to print
void FooMember::FooMember_printer() {
    std::cout << "I have no secret int." << std::endl;
    return;
};

int main() {

    Foo my_foo;
    my_foo.Foo_printer();
    my_foo.foo_member->FooMember_printer();

    return 0;
};

0 个答案:

没有答案