小编Rom*_*oma的帖子

从另一个线程调用shared_from_this但在shared_ptr初始化之后获取bad_weak_ptr

以某种方式p->start()被称为 - shared_from_this抛出bad_weak_ptr.
但正如你所看到的那样,p->start()被称为shared_ptr完全启动之后.

struct A : std::enable_shared_from_this<A> 
{
    std::thread* t = nullptr;
    A() {}
    ~A(){ 
        t->join(); 
        delete t; 
    }
    void f() { 
        try{
            auto p = this->shared_from_this(); 
            std::cout << "p:" << p.get() << "\n";
        } catch(...) { 
            std::cout << "Exception !!!\n"; 
        }
    }
    void start() { 
        t = new std::thread(&A::f,this); 
    }
};
std::shared_ptr<A> create() { 
    A* a = new A();
    std::shared_ptr<A> p(a);
    p->start();
    return p;
}
int main()
{   
    int …
Run Code Online (Sandbox Code Playgroud)

c++ multithreading stl shared-ptr

3
推荐指数
1
解决办法
224
查看次数

使用enable_if的模板函数参数推导 - 对指针的引用

也许有很好的解决方案适用于g ++ 4.6.{3,4}?您可以登录https://godbolt.org/

#include <type_traits>
class A{};
class B{};
class C{
    public:
    A* a;
    B* b;
};

template<typename T, typename std::enable_if<std::is_same<typename std::remove_reference<T>::type,A*>::value>::type* = nullptr >
void f(T&& t) { 
    return;
}

int main() { 
    C c;
    auto& cRef = c;
    f(cRef.a);
    f(c.a);
}
Run Code Online (Sandbox Code Playgroud)

g ++ /tmp/enable_if.cpp -std = c ++ 0x

/tmp/enable_if.cpp: In function ‘int main()’:
/tmp/enable_if.cpp:20:13: error: no matching function for call to ‘f(A*&)’
/tmp/enable_if.cpp:20:13: note: candidate is:
/tmp/enable_if.cpp:13:6: note: template<class T, typename std::enable_if<std::is_same<typename std::remove_reference<_MemPtr>::type, A*>::value, void>::type* <anonymous> …
Run Code Online (Sandbox Code Playgroud)

c++ c++11 c++03

1
推荐指数
1
解决办法
130
查看次数

Rust 泛型 - 特征、结构和关联类型

我来自 C++ 社区,正在切换到 Rust...并使用 Rust 泛型,任何人都可以解释为什么我在这个虚拟示例中收到此错误吗?

struct FF<T1, T2>(T1, T2);

trait FFt<T1, T2> {
    type t1 = T1;
    type t2 = T2;
    fn call<t1, t2>(&self, t_1: Self::t1, t_2: Self::t2);
};

impl<T1, T2> FFt<T1, T2> for FF<T1, T1> {
    fn call<T1, T2>(&self, t_1: Self::t1, t_2: Self::t2) {
        t_1.a = 1;
        t_2.b = 1;
    }
}

struct AA {
    a: i32,
    b: i32,
}
let fff: FF<AA, AA> = FF(AA { a: 0, b: 0 }, AA { a: 0, b: 0 …
Run Code Online (Sandbox Code Playgroud)

generics rust

0
推荐指数
1
解决办法
323
查看次数

标签 统计

c++ ×2

c++03 ×1

c++11 ×1

generics ×1

multithreading ×1

rust ×1

shared-ptr ×1

stl ×1